package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    private static final Integer IS_DEFAULT = 1;
    private static final Integer IS_NOT_DEFAULT = 0;

    @Autowired
    private AddressBookMapper addressBookMapper;
    /**
     * 查询当前登录用户的所有地址信息
     * @return
     */
    @Override
    public List<AddressBook> getList() {
        List<AddressBook> addressBooks = addressBookMapper.getList(BaseContext.getCurrentId());
        return addressBooks;
    }

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(IS_DEFAULT);
        addressBookMapper.add(addressBook);
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    @Override
    @Transactional
    public void setDefault(AddressBook addressBook) {
        // 先将该用户的地址全部设置为非默认地址
        AddressBook newAddressBook = AddressBook.builder()
                                            .userId(BaseContext.getCurrentId())
                                            .isDefault(IS_NOT_DEFAULT)
                                            .build();
        addressBookMapper.update(newAddressBook);

        // 设置默认地址
        addressBook.setIsDefault(IS_DEFAULT);
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    /**
     * 根据id修改地址
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void delete(Long id) {

        AddressBook addressBook = addressBookMapper.getDefault(BaseContext.getCurrentId());
        // 首先判断是否为默认地址
        if (addressBook.getId().equals(id)){
            throw new DeletionNotAllowedException(MessageConstant.ADDRESS_BOOK_IS_DEFAULT);
        }

        addressBookMapper.delete(id);
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public AddressBook getDefault() {
        AddressBook addressBook = addressBookMapper.getDefault(BaseContext.getCurrentId());
        return addressBook;
    }
}
